<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        // 1.二叉树定义
        function TreeNode(val, left, right) {
            this.val = (val === undefined ? 0 : val)
            this.left = (left === undefined ? null : left)
            this.right = (right === undefined ? null : right)
        }
        // 2.二叉树前序遍历
        var preorderTraversal = function (root) {
            let result = []
            let stack=[]
            if(root){
                stack.push(root)
            }
            while(stack.length>0){
                let node = stack.pop()
                result.push(node.val)
                if(node.right) stack.push(node.right)
                if(node.left) stack.push(node.left)
            }
            return result
        }
        // 3.二叉树中序遍历
        var orderTraversal = function (root) {
            let result = []
            let stack=[]
            let cur = root
            while(cur||stack.length>0){
                while(cur){
                    stack.push(cur)
                    cur = cur.left
                }
                cur = stack.pop()
                result.push(cur.val)
                cur=cur.right
            }
            
            return result
        }
        // 4.二叉树后序遍历
        var postorderTraversal = function (root) {
            let result = []
            let stack=[]
            stack.push(root)
            while(stack.length>0){
                let node = stack.pop()
                result.unshift(node.val)
                if(node.left){
                    stack.push(node.left)
                }
                if(node.right){
                    stack.push(node.right)
                }
            }
            return result
        }
        let root = new TreeNode(1)
        root.left = new TreeNode(2)
        root.right = new TreeNode(3)
        root.left.left = new TreeNode(4)
        root.left.right = new TreeNode(5)

        console.log(preorderTraversal(root))
        console.log(orderTraversal(root))
        console.log(postorderTraversal(root))
    </script>
</body>
</html>